package com.zzh.demo.core.handler;

import com.zzh.demo.core.exception.BusinessException;
import com.zzh.demo.core.model.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * description： 全局异常拦截处理 <br>
 * createTime: 2018/3/815:27 <br>
 *
 * @author zzh
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    private static final List<String> apiUrl = new ArrayList<>();

    static {
    }

    /**
     * 所有异常报错
     * @param response  响应
     * @param exception 异常
     * @return  错误提示信息
     */
    @ExceptionHandler(value=Exception.class)
    public Object allExceptionHandler(Exception exception, HttpServletResponse response) throws ServletException, IOException {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        log.error("发生异常", exception);
        //ajax请求返回501错误，
        // tab页面均通过ajax请求加载，所以去掉对ajax请求的判断，此判断不适用当前项目
//        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With")) || isApi(request.getRequestURI())) {
        if(isApi(request.getRequestURI())) {
            response.setStatus(501);
            if(exception instanceof BusinessException) {
                BusinessException e  = (BusinessException) exception;
                return ResponseModel.failure(e.getCode(), e.getMsg());
            }else {
                return ResponseModel.failure();
            }
        } else {
            response.setStatus(500);
            request.getRequestDispatcher("/gotoError").forward(request, response);
            return null;
        }
    }


    private boolean isApi(String uri) {
        for (String s : apiUrl) {
            if(uri.contains(s)) {
                return true;
            }
        }
        return false;
    }
}
